//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"bytes"
	"fmt"
	"strings"

	"atomgit.com/openlinksaas-org/search-proxy/core"
	"github.com/antchfx/htmlquery"
)

type PkgsParser struct{}

func (parser *PkgsParser) MatchUrl(url string) bool {
	return strings.HasPrefix(url, "https://pkgs.org/search")
}

func (parser *PkgsParser) Parse(url string) ([]*core.SearchEntry, error) {
	body, err := GetPage(url)
	if err != nil {
		return nil, err
	}

	doc, err := htmlquery.Parse(bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}
	fmt.Println(htmlquery.InnerText(doc))

	retList := []*core.SearchEntry{}
	descList := htmlquery.Find(doc, "//div[@class='card']//div[contains(@class,'card-body')]//td[@class='d-none d-md-table-cell']")
	for _, descEl := range descList {
		linkEl := htmlquery.FindOne(descEl.Parent, "//a")
		retList = append(retList, &core.SearchEntry{
			Title:   htmlquery.InnerText(linkEl),
			Url:     htmlquery.SelectAttr(linkEl, "href"),
			Summary: htmlquery.InnerText(descEl),
		})
	}
	return retList, nil
}
